import 'package:dio/dio.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_deer/demo/demo_page.dart';
import 'package:flutter_deer/dl/dl.dart';
import 'package:flutter_deer/l10n/deer_localizations.dart';
import 'package:flutter_deer/login/page/login_page.dart';
import 'package:flutter_deer/net/dio_utils.dart';
import 'package:flutter_deer/net/http_api.dart';
import 'package:flutter_deer/net/intercept.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/routers/not_found_page.dart';
import 'package:flutter_deer/setting/provider/theme_provider.dart';
import 'package:flutter_deer/ui/main_bindings.dart';
import 'package:flutter_deer/util/device_utils.dart';
import 'package:flutter_deer/util/handle_error_utils.dart';
import 'package:flutter_deer/util/log_utils.dart';
import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:oktoast/oktoast.dart';
import 'package:quick_actions/quick_actions.dart';
import 'package:sp_util/sp_util.dart';
// import 'package:url_strategy/url_strategy.dart';
import 'package:window_manager/window_manager.dart';

void main() async {
  // await GetStorage.init();
  //  debugProfileBuildsEnabled = true;
  //  debugPaintLayerBordersEnabled = true;
  //  debugProfilePaintsEnabled = true;
  //  debugRepaintRainbowEnabled = true;
  if (Constant.inProduction) {
    /// Release环境时不打印debugPrint内容
    debugPrint = (String? message, {int? wrapWidth}) {};
  }

  // await GetStorage.init();

  /// 异常处理
  handleError(() async {
    /// 确保初始化完成
    WidgetsFlutterBinding.ensureInitialized();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    if (Device.isDesktop) {
      await WindowManager.instance.ensureInitialized();
      windowManager.waitUntilReadyToShow().then((_) async {
        /// 隐藏标题栏及操作按钮
        // await windowManager.setTitleBarStyle(
        //   TitleBarStyle.hidden,
        //   windowButtonVisibility: false,
        // );
        /// 设置桌面端窗口大小 1920 1080 960 540
        const size = Size(1366, 768);
        // const size = Size(600, 500);
        await windowManager.setSize(size);
        await windowManager.setMinimumSize(size);

        // 显示原生的边框，支持放大缩小
        await windowManager.setResizable(true);

        /// 居中显示
        await windowManager.center();
        await windowManager.show();
        await windowManager.setPreventClose(false);
        await windowManager.setSkipTaskbar(false);

        // 隐藏原生标题栏
        await windowManager.setTitleBarStyle(TitleBarStyle.hidden);

        // 开发模式下显示窗口
        // print('kDebugMode--->$kDebugMode');
        // if (kDebugMode) {
        //   bool isAlwaysOnTop = await windowManager.isAlwaysOnTop();
        //   await windowManager.setAlwaysOnTop(!isAlwaysOnTop);
        // }
      });
    }

    /// 去除URL中的“#”(hash)，仅针对Web。默认为setHashUrlStrategy
    /// 注意本地部署和远程部署时`web/index.html`中的base标签，https://github.com/flutter/flutter/issues/69760
    // setPathUrlStrategy();

    /// sp初始化
    await SpUtil.getInstance();

    /// 1.22 预览功能: 在输入频率与显示刷新率不匹配情况下提供平滑的滚动效果
    GestureBinding.instance?.resamplingEnabled = true;
    // configureInjection(Environment.prod);
    configureDependencies(Environment.prod);
    // runApp(DatabaseProvider(child: MyApp()));
    // runApp(Obx(() => MyApp()));
    // runApp(PreviewApp());
    runApp(MyApp());
    // runApp(Main2App());
    // runApp(MyApp3());
    // runApp(OrderApp());
  });

  /// 隐藏状态栏，导航栏。为启动页、引导页设置全屏显示。完成后还原。
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
  // TODO(weilu): 启动体验不佳。状态栏、导航栏在冷启动开始的一瞬间为黑色，且无法通过隐藏、修改颜色等方式进行处理。。。
  // 相关问题跟踪：https://github.com/flutter/flutter/issues/73351
}

class MyApp extends StatelessWidget {
  MyApp({
    super.key,
    this.home,
  }) {
    Log.init();
    initDio();
    initQuickActions();
  }

  final Widget? home;
  static GlobalKey<NavigatorState> mNavigatorKey = GlobalKey();

  void initDio() {
    final List<Interceptor> interceptors = <Interceptor>[];

    /// 统一添加身份验证请求头
    interceptors.add(AuthInterceptor());

    /// 刷新Token
    interceptors.add(TokenInterceptor());

    /// 打印Log(生产模式去除)
    if (!Constant.inProduction) {
      interceptors.add(LoggingInterceptor());
    }

    /// 适配数据(根据自己的数据结构，可自行选择添加)
    // interceptors.add(AdapterInterceptor());
    configDio(
      baseUrl: HttpApi.baseUrl,
      interceptors: interceptors,
    );
  }

  void initQuickActions() {
    if (Device.isMobile) {
      const QuickActions quickActions = QuickActions();
      if (Device.isIOS) {
        // Android每次是重新启动activity，所以放在了splash_page处理。
        // 总体来说使用不方便，这种动态的方式在安卓中局限性高。这里仅做练习使用。
        quickActions.initialize((String shortcutType) async {
          if (shortcutType == 'demo') {
            mNavigatorKey.currentState?.push<dynamic>(MaterialPageRoute<dynamic>(
              builder: (BuildContext context) => const DemoPage(),
            ));
          }
        });
      }

      quickActions.setShortcutItems(<ShortcutItem>[
        const ShortcutItem(type: 'demo', localizedTitle: 'Demo', icon: 'flutter_dash_black'),
      ]);
    }
  }

  @override
  Widget build(BuildContext context) {
    final themeVM = Get.put(ThemeVM());

    /// Toast 配置
    return OKToast(
        backgroundColor: Colors.black54,
        textPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
        radius: 20.0,
        position: ToastPosition.bottom,
        child: GetMaterialApp(
          title: 'Edge',
          // showPerformanceOverlay: true, //显示性能标签
          // debugShowCheckedModeBanner: false, // 去除右上角debug的标签
          // checkerboardRasterCacheImages: true,
          // showSemanticsDebugger: true, // 显示语义视图
          // checkerboardOffscreenLayers: true, // 检查离屏渲染
          initialBinding: MainBindings(),
          debugShowCheckedModeBanner: false,
          theme: themeVM.getTheme(),
          darkTheme: themeVM.getTheme(),
          themeMode: themeVM.currentTheme.value,
          home: home ?? const LoginPage(),
          localizationsDelegates: DeerLocalizations.localizationsDelegates,
          supportedLocales: DeerLocalizations.supportedLocales,
          // locale: localeState.locale,
          navigatorKey: mNavigatorKey,
          builder: (BuildContext context, Widget? child) {
            final themeVM = Get.find<ThemeVM>();
            return Obx(() {
              return MediaQuery(
                data: MediaQuery.of(context).copyWith(textScaler: TextScaler.noScaling),
                child: Theme(
                  data: themeVM.getTheme(), // 应用当前主题
                  child: child!,
                ),
              );
            });
          },

          /// 因为使用了fluro，这里设置主要针对Web
          onUnknownRoute: (_) {
            return MaterialPageRoute<void>(
              builder: (BuildContext context) => const NotFoundPage(),
            );
          },
          // restorationScopeId: 'app',
        ));
  }
}
